/**
 * Created by Administrator on 2015/12/5.
 */

var d = new Date();
console.log(d);
console.log(d.getTime());//
console.log(Date.now());
console.log(d.toDateString());
console.log(d.toJSON());//把日期转化为JSON对象2015-12-05T09:07:54.000Z
/**
 * 格式化日期
 * @param date
 * @param fmt
 * @returns {*}
 */
function format(date,fmt){
    if(date instanceof Date){
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }else{
        return '';
    }
}
console.log(format(new Date,'yyyy年MM月dd日'));

/**
 * dateFormat(new Date(),'{y}年{M}月{d}日 {h}点{m}分{s}秒')
 * @param date
 * @param fmt
 * @returns {*}
 */
function dateFormat(date,fmt){
    if(date instanceof Date){
        date = {
            y:date.getFullYear(),
            M:date.getMonth(),
            d:date.getDay(),
            h:date.getHours(),
            m:date.getMinutes(),
            s:date.getSeconds()
        };
        return replace(fmt,date);
    }else {
        return '';
    }

}
/**
 * sample 1:
 * '''js
 * var template = 'Hello {name}!'
 * var obj = {name:'John'}
 * console.log(replace(template,obj)) //out: Hello John!
 *
 * '''js
 * sample 2:
 * var template = 'Hello {user.name}!'
 * var obj = {user:{name:'Christoper Smith'}};
 * console.log(replace(template,obj))//out:Hello Christoper Smith!
 * @param template
 * @param obj
 * @returns {*}
 */
function replace(template,obj){
    var pattern = /{([_\w\.]+)}/g;
    return template.replace(pattern,function(match,p1,offset,string){
        var arr = p1.split('.');
        if(arr.length > 1){
            var i = 0;
            var len = arr.length;
            var subObj = obj[arr[0]];
            while(typeof subObj === 'object' && i < len){
                i = i + 1;
                subObj = subObj[arr[i]];
            }
            if(i === len-1){
                if(subObj === undefined){
                    return "";
                }else{
                    return subObj;
                }
            }else {
                return "";
            }
        }else{
            var ret = obj[p1]
            if(ret === undefined)
            {
                return "";
            }else{
                return ret;
            }
        }

    })
}